<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        required
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名',validator:fn}]"
      />
      <van-field
        v-model="password"
        type="password"
        required
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import instance from "@/api/api";
import debounce from '@/utils/debounce'
import { Toast } from 'vant';
export default {
  name: 'Loginview',

  data() {
    return {
      username: '',
      password: '',
      debounceLoginfn:null,
      nextTo:'',//登录成功后跳转到哪
    };
  },

  mounted() {
    
  },
  
  created(){
    console.log(this.$route.params.id)
    this.debounceLoginfn = debounce(this.loginfn,2000)
    this.nextTo = this.$route.params.id
  },

  methods: {
    async loginfn(){
      //登录验证业务
      //登录验证
      let {data} = await instance.post('/login')
      console.log(data)
      let token = data.token;
      //把token存放到vuex中
      this.$store.commit('settoken',token) //提交给mutation
      let nextTo = this.nextTo;
      console.log(nextTo)
      Toast.success({
        type:"success",
        message:"登录成功",
        onClose:()=>{
          this.$router.push({name:nextTo})
        }
      });
    },

  
    onSubmit(a){
      //用户行为事件
      this.debounceLoginfn()
    },

    fn(a,b){
      //a输入表单的值,b是一个对象，里面是当前验证的规则
      //console.log(a,b)
    }
  },
};
</script>

<style lang="less" scoped>

</style>